package BitCreeekClient;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

public class PeerConfig {
	
	private static Properties config;
	
	final static int SERVER_PORT = 6800;
	
	// dirs
	private static File getBitCreekConfigDir( ) {
		return new File( System.getProperty( "user.home" ) + "/.BitCreekConfig" );
	}
	private static File getDownloadsDir( ) {
		return new File( getDownloadsDirPath() );
	}
	static File getTorrentsDir( ) {
		return new File( getTorrentsDirPath() );
	}
	private static void createPeerDirs( ) {
		
		getDownloadsDir().mkdir();
		getTorrentsDir().mkdir();
	}
	
	private static File getConfigFile( ) {
		return new File( getBitCreekConfigDir() + "/BitCreek.cfg" );
	}
	
	// constructor
	public static void loadConfig( ) {		
		try {
			InputStream is = new FileInputStream( getConfigFile() );
			config.load( is );
			setServerPort( SERVER_PORT );
			is.close();
		} catch (Exception e) { }
	}
	
	public static void initConfig() throws IOException {
		config = new Properties();
		getBitCreekConfigDir().mkdir();
		loadConfig();

		setConfigDirPath();
		String basePath = getConfigDirPath();

		// Default INIT
		if ( getDownloadsDirPath() == null || getDownloadsDirPath() == ""  )
			setDownloadsDiPath( basePath+"/downloads/" );
		if ( getTorrentsDirPath() == null || getTorrentsDirPath() == ""  )
			setTorrentsDirPath( basePath+"/torrents/" );

		createPeerDirs( );
		
		
		
		
		
		
		setConfigDirPath();
	}
	
	public static void saveConfig( ) throws IOException {
		OutputStream os = new FileOutputStream( getConfigFile() );
		config.store( os, "BitCreek 1.0v" );
		os.close( );
	}
	
	// user info
	private static void setConfigDirPath( ) {
		config.setProperty( "BC_configDir", System.getProperty( "user.home" ) + "/.BitCreekConfig"  );
	}
	public static String getConfigDirPath(  ) {
		return config.getProperty("BC_configDir");
	}
	public static void setDownloadsDiPath( String path ) {
		config.setProperty( "BC_downloadsDir", path   );
		getDownloadsDir().mkdir();
	}
	public static String getDownloadsDirPath( ) {
		return config.getProperty("BC_downloadsDir");
	}
	public static void setTorrentsDirPath( String path ) {
		config.setProperty( "BC_torrentsDir", path   );
		getTorrentsDir().mkdir();
	}
	public static String getTorrentsDirPath( ) {
		return config.getProperty("BC_torrentsDir");
	}
	
	// server address
	public static String getServerAddress( ) {
		return config.getProperty( "serverAddress", "127.0.0.1" );
	}
	public static void setServerAddress( String s )	{
		config.setProperty( "serverAddress", s );
	}
	
	// server port
	public static int getServerPort( )	{
		return SERVER_PORT;
	}
	public static void setServerPort( int port ) {
		config.setProperty( "serverPort", ""+port );
	}

}
